function handles = loadTraces(handles, mode)
% loadTraces -- private version for mapAnalysis2p0 gui
%
% MODES:
% 0 -- subset of traces in directory selected manually
% 1 -- all map traces in for one map automatically selected
% 2 -- multiple maps, identified manually
% 3 -- multiple maps, designated in M-file
%
% Notes:
% - for convenience, general physiol traces are to some extent treated as a 'map'
% 
% See also
%
% Editing:
% gs march, april 2005
% gs march, april 2006 - modified for ephus and 'turbo' maps
% --------------------------------------------------------------------

% reset
handles = resetAnalysis('load', handles);

try % ... to find the default directory (set this in initializeAnalysisParameters.m)
    cd(handles.data.analysis.defaultDataDir);
catch
    disp('Unable to find default data directory. Modify initializeAnalysisParameters.m');
end

% determine how many maps to analyze
if mode == 0 | mode == 1
    handles.data.analysis.numberOfMaps = 1;
elseif mode == 2
    numberOfMaps = inputdlg('How many maps to analyze? ');
    handles.data.analysis.numberOfMaps = str2num(numberOfMaps{1});
elseif mode == 3
    dataMfile = inputdlg('Enter name of data M-file (e.g. g1091P1)');
    try
        eval(['handles.data.dataMfile = ' dataMfile{1} ';']);
        handles.data.analysis.numberOfMaps = numel(handles.data.dataMfile.mapNumbers);
        handles.data.dataMfile.experiment = handles.data.dataMfile.experiment(1:6);
    catch
        warndlg('loadTraces: Problem loading specified data M-file.');
        warning(lasterr)
        return
    end
end

try
    cd(handles.data.analysis.uncagingPathName); 
catch
end

if mode ~= 3
    handles.data.analysis.mapNumbers = [];
elseif mode == 3
    handles.data.analysis.mapNumbers = []; % gs20070311: will this work?
end
for m = 1 : handles.data.analysis.numberOfMaps
    
    handles.data.map.mapActive = [];
    
    % select the traces to load - step 1
    try
        if mode < 3
            [Fname, Pname] = uigetfile(...
                {   '*.xsg', 'Ephus traces (*.xsg)'; ...
                    '*.mwf', 'TidalWave traces (*.mwf)'; ...
                    '*.*', 'All files (*.*)'}, ...
                'Select any trace.');
                    cd(Pname);

        elseif mode == 3
            mapNumID = translateMapNum(handles.data.dataMfile.mapNumbers(m));
            Fname = [handles.data.dataMfile.experiment mapNumID '0001.xsg'];
            % e.g.: gs2224MAAA0001.xsg
            mapNumStr = num2str(handles.data.dataMfile.mapNumbers(m));
            if numel(mapNumStr) == 1
                mapNumStr = ['0' mapNumStr];
            end % TODO: this probably needs to be fixed for larger #s
            % ------- PROBLEM (START) ----------
            Pname = [handles.data.dataMfile.pathBaseName 'map' mapNumStr '\'];
            % pathBaseName stored incorrectly:
            % e.g. C:\_Cartography\matlab\dataMfiles\Gordon\gs22\traces\map01\
            % should be C:\_Data\Gordon\gs2224\map01
            % quick fix:
            localpath1 = 'C:\_Data\Gordon\'; % <<<<========= settable
            localpath2 = 'D:\DATA\CMdata\'; % <<<<========= settable
            localpath3 = 'E:\DATA\CMdata\'; % <<<<========= settable
            expStr = handles.data.dataMfile.experiment(1:6);
            Pname = [localpath1 expStr '\map' mapNumStr '\'];
            try
                cd(Pname);
            catch
                try
                    Pname = [localpath2 expStr '\map' mapNumStr '\'];
                    cd(Pname);
                catch
                    try
                        Pname = [localpath3 expStr '\map' mapNumStr '\'];
                        cd(Pname);
                    catch
                        warndlg('Unable to find usable local path. Edit loadTraces to provide path.');
                    end
                end
            end
            % ------- PROBLEM (END) ----------
        end
%         cd(Pname);
        Dname = cd;
        disp(['Processing traces in: ' Dname]);
        [pathstr,name,ext,versn] = fileparts(fullfile(Pname, Fname));
        % gs 2006 03 11 rewrite starts about here
        % ditto for 2006 april turbo-map stuff
        direc = dir(['*' ext]);
        handles.data.map.mapActive.numTraces = numel(direc);
        handles.data.map.mapActive.directory = cd;
        
        if strcmp(ext, '.mwf')
            handles.data.analysis.mapNumbers = [handles.data.analysis.mapNumbers str2num(handles.data.map.mapActive.directory(end-1:end))];
        elseif strcmp(ext, '.xsg')
            str = handles.data.map.mapActive.directory;
            i = strfind(str, 'map');
            try
                %             handles.data.analysis.mapNumbers = [handles.data.analysis.mapNumbers ...
                %                     str2num(handles.data.map.mapActive.directory(end-1:end))];
                handles.data.analysis.mapNumbers = [handles.data.analysis.mapNumbers ...
                        str2num(handles.data.map.mapActive.directory(max(i)+3:end))];
            catch
                warning('loadTraces:mapNumbers', 'Problem extracting map number from directory name');
            end
        end
        handles.data.map.mapActive.uncagingPathName = Pname;
        handles.data.analysis.uncagingPathName = Pname; % save info for convenience
        hereFile = Fname;
        period = findstr('.', Fname);
        fnum = str2num(Fname( period-4 : period-1 ));
        Fname = Fname( 1 : period-5);
        handles.data.map.mapActive.baseName = Fname;
        handles.data.map.mapActive.traceNumber = fnum;

        % P1 P2 stuff -- for dual/pair recordings 
        % TODO: will have to rewrite this segment for ephus traces
        handles.data.analysis.patchChannel = 'P1'; % default
        if mode == 1 || mode == 2
            lastFile = direc(numel(direc));
            i = strfind(lastFile.name, 'P2');
            if ~isempty(i) % i.e., there must be P2 traces ...
                patchChannel = questdlg('Choose patch channel to process', ...
                    'Select patch channel', 'P1', 'P2', 'P1');
                handles.data.analysis.patchChannel = patchChannel;
                handles.data.map.mapActive.numTraces = handles.data.map.mapActive.numTraces/2;
                j = strfind(handles.data.map.mapActive.baseName, 'P1');
                handles.data.map.mapActive.baseName(j+1) = patchChannel(2);
            end
        end
        
    catch
        error(lasterror);
    end
    
    % step 2
    if mode == 0
        names = selectFilesFromList(Pname, ext);
        for n = 1 : size(names,1)
            handles.data.map.mapActive.filenames(n, :) = names{n};
        end
        handles.data.map.mapActive.numTraces = size(names,1);
    elseif mode == 1 || mode == 2 || mode == 3
        handles.data.map.mapActive.filenames = {};
        for nn = 1 : handles.data.map.mapActive.numTraces
            if nn < 10
                zeroStr = '000';
            elseif nn < 100
                zeroStr = '00';
            else
                zeroStr = '0';
            end
            handles.data.map.mapActive.filenames(nn,:) = ...
                {[handles.data.map.mapActive.baseName zeroStr num2str(nn) ext]};
        end
    end
    
    % transfer the map data set to its own numbered map directory:
    string = (['handles.data.map.map' num2str(m)]);
    eval([string '= handles.data.map.mapActive;']);
end
waitbar(0.35, handles.hWaitBar, 'Loading, please wait.');



% nM = handles.data.analysis.numberOfMaps
% nT = handles.data.map.mapActive.numTraces

for m = 1 : handles.data.analysis.numberOfMaps
    
    % transfer the map data sets back to the active map directory:
    string = (['handles.data.map.map' num2str(m)]);
    eval(['handles.data.map.mapActive = ' string ';']);
    
    % LOAD loop
    disp('Please wait ...')
    
%     for n = 1 : size(handles.data.map.mapActive.filenames,1)
    for n = 1 : handles.data.map.mapActive.numTraces
        fname = [handles.data.map.mapActive.uncagingPathName ...
                char(handles.data.map.mapActive.filenames(n,:))];
        
        switch ext
%             case '.mwf'
%                 waveProps = loadWaveDataFromStructure(fname);
%                 [r,c] = size(waveProps.data);
%                 if r ~= 1
%                     waveProps.data = waveProps.data';
%                 end
%                 handles.data.map.mapActive.dataArray(:, n) = waveProps.data;
%                 
%                 handles.data.map.mapActive.physHeader = waveProps.UserData;
%                 %     patterns = getHeaderFieldPhys(state.uncaging.pairs.physHeader, 'patterns');
%                 %     number = getfield(patterns.num1, 'number');
%                 %     amplitude = getfield(patterns.num1, 'amplitude');
%                 %     width = getfield(patterns.num1, 'width');
%                 %     srOut = getfield(patterns.num1, 'srOut');
%                 %     isi = getfield(patterns.num1, 'isi');
%                 %     totalTime = getfield(patterns.num1, 'totalTime');
%                 %     offset = getfield(patterns.num1, 'offset');
%                 %     addComp = getfield(patterns.num1, 'addComp');
%                 %     delay = getfield(patterns.num1, 'delay');
%                 %     patternName = getfield(patterns.num1, 'patternName');
%                 %     ramp = getfield(patterns.num1, 'ramp');
%                 %
%                 %     % stim reconstruction
%                 %     stimArray(:, n) = zeros(1:length(data, 1));
%                 
%                 try
%                     handles.data.map.mapActive.uncagingHeader = handles.data.map.mapActive.physHeader.uncagingHeader;
%                     handles.data.map.mapActive.physHeader.uncagingHeader = [];
%                     %     %         triggerTime = getHeaderFieldPhys(waveProps.UserData, 'triggerTime');
%                     %     %         state.uncaging.map.triggerTime = [state.uncaging.map.triggerTime; triggerTime];
%                     % %     triggerTime = datestr(waveProps.timeStamp);
%                     % %     state.uncaging.map.triggerTime = [state.uncaging.map.triggerTime; triggerTime];
%                     
%                     % grab selected header info
%                     %     handles.data.acq.deltaX(n) = getHeaderFieldPhys(handles.data.map.uncagingHeader, 'deltaX');
%                     %     handles.data.acq.deltaY(n) = getHeaderFieldPhys(handles.data.map.uncagingHeader, 'deltaY');
%                     handles.data.map.mapActive.laserIntensity(n) = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'laserIntensity');
%                 catch
%                 end
%                 
            case '.xsg'
                traceFile = load(fname,'-mat'); 
%                 assignin('base', 'traceFile', traceFile) %% for debugging
                
                % use data source specified in gui
                uicell = get(handles.aiProgram, 'String');
                uistr = uicell{get(handles.aiProgram, 'Value')};
                uinumstr = num2str(get(handles.aiTraceNum, 'Str'));
                dataSourceStr = ['traceFile.data.' uistr '.trace_' uinumstr];
                try
                    data = eval(dataSourceStr);
                catch
                    disp('loadTraces: problem with selected data source');
                    return
                end
                [r,c] = size(data);
                if r ~= 1
                    data = data';
                end
                if isfield(traceFile.header, 'headerGUI')
                    handles.data.map.mapActive.headerGUI = traceFile.header.headerGUI.headerGUI;
                end
                handles.data.map.mapActive.physHeader = traceFile.header.ephys.ephys;
                handles.data.map.mapActive.uncagingHeader = traceFile.header.mapper.mapper;
                handles.data.map.mapActive.physHeader.uncagingHeader = [];
                handles.data.map.mapActive.scopeHeader = traceFile.header.scopeGui.ephysScopeAccessory; % gs 20060625
                handles.data.map.mapActive.acquirerHeader = traceFile.header.acquirer.acquirer; % gs 20060625
                handles.data.map.mapActive.imagingSysHeader = traceFile.header.imagingSys.imagingSys; % gs 20080627

                if handles.data.map.mapActive.numTraces ~= 1 % NON-TURBO maps
                    handles.data.map.mapActive.dataArray(:, n) = data;
                    
                elseif handles.data.map.mapActive.numTraces == 1 & mode ~= 0 % TURBO map
                    traceletLength = handles.data.map.mapActive.uncagingHeader.isi * handles.data.map.mapActive.physHeader.sampleRate;
                    handles.data.map.mapActive.dataArray = reshape(data, [], length(data)/traceletLength);
                    
                elseif handles.data.map.mapActive.numTraces == 1 & mode == 0 % handles unusual case of single non-turbo-map (e.g. gen phys) trace in directory
                    handles.data.map.mapActive.dataArray(:, n) = data;
                    
                end
                handles.data.map.mapActive.laserIntensity(n) = handles.data.map.mapActive.uncagingHeader.specimenPlanePower;
                % NB -- for turbomaps, is this the correct value for the power????? i.e., was this the correctly computed value for this trace, or the prev trace?

            otherwise
                warning('loadTraces', 'unrecognized trace file type');
                return
        end
        
    end
    
    switch ext
%         case '.mwf'
%             handles.data.acq.sampleRate = handles.data.map.mapActive.physHeader.inputRate;
%             handles.data.acq.clampMode = handles.data.map.mapActive.physHeader.modeString;
%             handles.data.acq.breakInTime = handles.data.map.mapActive.scopeHeader.breakInTime; % gs 20060625
%             handles.data.acq.triggerTime = handles.data.map.mapActive.acquirerHeader.triggerTime; % gs 20060625
%             try
%                 handles.data.map.mapActive.mapPattern = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'pulsePattern');
%                 handles.data.map.mapActive.mapSpacing = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'mapSpacing');
%                 handles.data.acq.imageXrange = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'totalXpath');
%                 handles.data.acq.imageYrange = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'totalYpath');
%                 handles.data.acq.somaX = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'somaPosX');
%                 handles.data.acq.somaY = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'somaPosY');
%                 handles.data.acq.somaZ = getHeaderFieldPhys(handles.data.map.mapActive.uncagingHeader, 'somaPosZ');
%             catch
%             end
%             
%             % avg laser intensity
%             try
%                 handles.data.acq.avgLaserIntensity = [handles.data.acq.avgLaserIntensity ...
%                         mean(handles.data.map.mapActive.laserIntensity)];
%             catch
%                 warning('loadTraces: problem computing average laser intensity');
%             end
%             
        case '.xsg'
            handles.data.acq.sampleRate = handles.data.map.mapActive.physHeader.sampleRate;
            a = fieldnames(handles.data.map.mapActive.physHeader.amplifierSettings);
            b = eval(['handles.data.map.mapActive.physHeader.amplifierSettings.' a{1} '.mode']);
            handles.data.map.mapActive.physHeader.modeString = b;
            handles.data.acq.clampMode = handles.data.map.mapActive.physHeader.modeString;
            handles.data.acq.breakInTime = handles.data.map.mapActive.scopeHeader.breakInTime; % gs 20060625
            try
                handles.data.acq.triggerTime = handles.data.map.mapActive.acquirerHeader.triggerTime; % gs 20060625
            catch
                handles.data.acq.triggerTime = '';
            end
            
%             mp = handles.data.map.mapActive.uncagingHeader.mapPattern;
%             angleFactor = 0; %% TODO:
%             transposeFactor = 0; %% TODO:
%             MP = eval(['map' mp '(' num2str(angleFactor) ',' num2str(transposeFactor) ')']);
%             handles.data.map.mapActive.mapPattern = MP;
            handles.data.map.mapActive.mapPattern = handles.data.map.mapActive.uncagingHeader.mapPatternArray;
            %% TODO: incorporate non-equal X and Y spacing; also incorporate xPatternOffset, yPatternOffset
            xSpacing = handles.data.map.mapActive.uncagingHeader.xSpacing;
            handles.data.map.mapActive.xSpacing = xSpacing;
            ySpacing = handles.data.map.mapActive.uncagingHeader.ySpacing;
            handles.data.map.mapActive.ySpacing = ySpacing;
            if xSpacing == ySpacing
                handles.data.map.mapActive.mapSpacing = xSpacing;
            else 
                handles.data.map.mapActive.mapSpacing = xSpacing;
                warning('loadTraces: different X and Y spacing. Using X spacing by default.');
            end
                        
            handles.data.acq.mapPatternName = handles.data.map.mapActive.uncagingHeader.mapPattern; % this is a string; not to be confused with the array, stored elsewhere as 'mapPattern'
            handles.data.acq.xPatternOffset = handles.data.map.mapActive.uncagingHeader.xPatternOffset;
            handles.data.acq.yPatternOffset = handles.data.map.mapActive.uncagingHeader.yPatternOffset;
            handles.data.acq.spatialRotation = handles.data.map.mapActive.uncagingHeader.spatialRotation;
            
            try
                handles.data.acq.imageXrange = handles.data.map.mapActive.imagingSysHeader.xMicrons;
                handles.data.acq.imageYrange = handles.data.map.mapActive.imagingSysHeader.yMicrons;
            catch
                try
                    handles.data.acq.imageXrange = handles.data.map.mapActive.uncagingHeader.videoHorizontalDistance;
                    handles.data.acq.imageYrange = handles.data.map.mapActive.uncagingHeader.videoVerticalDistance;
                catch %% TODO: implement these parameters properly
                    %                 handles.data.map.mapActive.uncagingHeader.videoHorizontalDistance = 810;
                    %                 handles.data.map.mapActive.uncagingHeader.videoHorizontalDistance = 2000;
                    handles.data.map.mapActive.uncagingHeader.videoHorizontalDistance = 2666;
                    handles.data.acq.imageXrange = handles.data.map.mapActive.uncagingHeader.videoHorizontalDistance;
                    %                 handles.data.map.mapActive.uncagingHeader.videoVerticalDistance = 605;
                    %                 handles.data.map.mapActive.uncagingHeader.videoVerticalDistance = 1500;
                    handles.data.map.mapActive.uncagingHeader.videoVerticalDistance = 2000;
                    handles.data.acq.imageYrange = handles.data.map.mapActive.uncagingHeader.videoVerticalDistance;
                    disp('loadTraces: using default values for videoHorizontalDistance and videoVerticalDistance');
                end
            end
            if isempty(handles.data.map.mapActive.uncagingHeader.soma1Coordinates)
                handles.data.acq.somaX = handles.data.map.mapActive.uncagingHeader.soma1Coordinates;
                handles.data.acq.somaY = handles.data.map.mapActive.uncagingHeader.soma1Coordinates;
            else
                handles.data.acq.somaX = handles.data.map.mapActive.uncagingHeader.soma1Coordinates(1);
                handles.data.acq.somaY = handles.data.map.mapActive.uncagingHeader.soma1Coordinates(2);
            end
            try
                handles.data.acq.somaZ = handles.data.map.mapActive.uncagingHeader.somaZ;
            catch
                handles.data.acq.somaZ = [];
            end
            % avg laser intensity
            try
                handles.data.acq.avgLaserIntensity = [handles.data.acq.avgLaserIntensity ...
                        mean(handles.data.map.mapActive.laserIntensity)];
            catch
                warning('loadTraces: problem computing average laser intensity');
            end

        otherwise
            warning('loadTraces', 'unrecognized trace file type');
            return
    end
    
    % transfer the map data set to its own numbered map directory:
    string = (['handles.data.map.map' num2str(m)]);
    eval([string '= handles.data.map.mapActive;']);
    
end


% INFO PANEL display

% experiment name, date, break-in time, number of maps

% k = strfind(handles.data.analysis.uncagingPathName, '\');
% handles.data.analysis.experimentName = ...
%     handles.data.analysis.uncagingPathName(k(end-3)+1:k(end-2)-1);

% try % basically a kluge to get this to work for ephus ... gs 2006 04 28 -- should re-do more robustly
%     k = strfind(handles.data.map.mapActive.baseName, 'map');
%     handles.data.analysis.experimentName = handles.data.map.mapActive.baseName(1 : (k-1));
% catch
%     handles.data.analysis.experimentName = handles.data.map.mapActive.baseName(1 : 6);
% end
% set(handles.experimentName, 'String', handles.data.analysis.experimentName);

if strcmp(ext, '.mwf')
    k = strfind(handles.data.map.mapActive.baseName, 'map');
    handles.data.analysis.experimentName = handles.data.map.mapActive.baseName(1 : (k-1));
elseif strcmp(ext, '.xsg')
    handles.data.analysis.experimentName = handles.data.map.mapActive.baseName(1 : 6);
end
set(handles.experimentName, 'String', handles.data.analysis.experimentName);

% date
if ~isempty(handles.data.acq.triggerTime)
    set(handles.experimentDate, 'String', [datestr(datenum(handles.data.acq.triggerTime), 'ddd') ', ' ...
            datestr(datenum(handles.data.acq.triggerTime), 1)]);
else
    set(handles.experimentDate, 'String', 'not noted');
end
% break-in time
if ~isempty(handles.data.acq.breakInTime)
    set(handles.breakInTime, 'String', datestr(datenum(handles.data.acq.breakInTime), 16));
else
    set(handles.breakInTime, 'String', 'not noted');
end
% trigger time
if ~isempty(handles.data.acq.triggerTime)
    set(handles.triggerTime, 'String', datestr(datenum(handles.data.acq.triggerTime), 16));
else
    set(handles.triggerTime, 'String', 'not noted');
end

set(handles.numberOfMaps, 'String', num2str(handles.data.analysis.numberOfMaps));
set(handles.mapNumbers, 'String', num2str(handles.data.analysis.mapNumbers)); % probably convert this to letters instead of numbers
% catch
%     disp('loadTraces: enter break-in time in gui. (optional)');
%     set(handles.experimentDate, 'Enable', 'on');
%     set(handles.breakInTime, 'Enable', 'on');
% end

% register and display clamp mode
set(handles.clampMode, 'String', handles.data.acq.clampMode);
clampMode = handles.data.acq.clampMode;
switch clampMode
    case {'V-Clamp', 'V-Track'}
        handles.data.analysis.currentClamp = 0;
        %         handles.data.analysis.responsesInvertedFlag = 0;
    case {'I = 0', 'I-Clamp', 'I-Clamp Fast', 'I-Clamp Normal'}
        handles.data.analysis.currentClamp = 1; 
        %         handles.data.analysis.responsesInvertedFlag = 1;
    otherwise
end

try
    % calc and display avg laser intensity
    handles.data.acq.overallAvgLaserIntensity = mean(handles.data.acq.avgLaserIntensity);
    avgmW = handles.data.acq.overallAvgLaserIntensity;
    % GS20080324 -- removed the rounding
%     avgmW = round(handles.data.acq.overallAvgLaserIntensity * 10) / 10;
    set(handles.laserIntensity, 'String', num2str(avgmW));
catch
    warning('loadTraces: problem calculating overall average laser intensity');
end
% display map spacing
try
    if handles.data.map.mapActive.xSpacing == handles.data.map.mapActive.ySpacing
        set(handles.mapSpacing, 'String', num2str(handles.data.map.mapActive.mapSpacing));
    else
        set(handles.mapSpacing, 'String', ...
            [num2str(handles.data.map.mapActive.xSpacing) ' ' num2str(handles.data.map.mapActive.ySpacing)]);
    end
catch % this is a temporary kluge for new/old compatibility
end

% map offsets and spatial rotation
set(handles.mapPatternName, 'String', handles.data.acq.mapPatternName);
% set(handles.mapPatternName, 'String', num2str(round(handles.data.acq.mapPatternName)));
set(handles.xPatternOffset, 'String', num2str(round(handles.data.acq.xPatternOffset)));
set(handles.yPatternOffset, 'String', num2str(round(handles.data.acq.yPatternOffset)));
set(handles.spatialRotation, 'String', num2str(round(handles.data.acq.spatialRotation)));

% display cell location -- X and Y
set(handles.somaX, 'String', num2str(round(handles.data.acq.somaX)));
set(handles.somaY, 'String', num2str(round(handles.data.acq.somaY)));

% transformed soma position
[handles.data.acq.somaXnew, handles.data.acq.somaYnew] = somaPositionTransformer(...
    handles.data.acq.somaX, handles.data.acq.somaY, handles.data.acq.spatialRotation, ...
    handles.data.acq.xPatternOffset, handles.data.acq.yPatternOffset);
set(handles.somaXnew, 'String', num2str(round(handles.data.acq.somaXnew)));
set(handles.somaYnew, 'String', num2str(round(handles.data.acq.somaYnew)));

% soma Z. Use header value if available, or if retain checkbox off
if ~isempty(handles.data.acq.somaZ) % NB: overrides the retain option
    set(handles.somaZ, 'String', num2str(round(handles.data.acq.somaZ)));
elseif isempty(handles.data.acq.somaZ) && ~get(handles.retainForNextCell, 'Value')
    set(handles.somaZ, 'String', num2str(round(handles.data.acq.somaZ)));
else
    disp('loadTraces: possible problem with soma Z value. Check for accuracy.');
end

% --------- reset cell params
% Rs
handles.data.map.mapAvg.rseriesAvg = [];
set(handles.rseriesAvg, 'String', num2str(handles.data.map.mapAvg.rseriesAvg));

% Ri (= Rm)
handles.data.map.mapAvg.rmembraneAvg = [];
set(handles.rmembraneAvg, 'String', num2str(handles.data.map.mapAvg.rmembraneAvg));

% Cm
handles.data.map.mapAvg.cmembraneAvg = [];
set(handles.cmembraneAvg, 'String', num2str(handles.data.map.mapAvg.cmembraneAvg));

% tau
handles.data.map.mapAvg.tauAvg = [];
set(handles.tauAvg, 'String', num2str(handles.data.map.mapAvg.tauAvg));


% ---------------- Keep / re-initialize user-defined parameters -----------------------------------
if ~get(handles.retainForNextCell, 'Value')
    
    % cellType
    handles.data.analysis.cellType = 'neuron';
    set(handles.cellType, 'String', handles.data.analysis.cellType);

    % Vrest
    handles.data.analysis.Vrest = [];
    set(handles.Vrest, 'String', num2str(handles.data.analysis.Vrest));

    % Vhold
    handles.data.analysis.Vhold = [];
    set(handles.Vhold, 'String', num2str(handles.data.analysis.Vhold));

    % animalAge
    % handles.data.acq.animalAge = get(handles.animalAge, 'String');
    % if isnumeric(handles.data.acq.animalAge)
    %     handles.data.acq.animalAge = num2str(handles.data.acq.animalAge);
    % end
    % -------------------------------
    % uncomment to enable re-set:
    handles.data.analysis.animalAge = [];
    set(handles.animalAge, 'String', num2str(handles.data.analysis.animalAge));
    % -------------------------------

    % exptCondition
    % handles.data.analysis.exptCondition = get(handles.exptCondition, 'String');
    % if isnumeric(handles.data.analysis.exptCondition)
    %     handles.data.analysis.exptCondition = num2str(handles.data.analysis.exptCondition);
    % end
    handles.data.analysis.exptCondition = '';
    set(handles.exptCondition, 'String', handles.data.analysis.exptCondition);

    % notes
    % handles.data.analysis.notes = get(handles.notes, 'String');
    % if isnumeric(handles.data.analysis.notes)
    %     handles.data.analysis.notes = num2str(handles.data.analysis.notes);
    % end
    % notes
    handles.data.analysis.notes = '';
    set(handles.notes, 'String', handles.data.analysis.notes);


    % fieldAName
    handles.data.analysis.fieldAName = get(handles.fieldAName, 'String');
    if isnumeric(handles.data.analysis.fieldAName)
        handles.data.analysis.fieldAName = num2str(handles.data.analysis.fieldAName);
    end

    % fieldAVal
    % handles.data.analysis.fieldAVal = get(handles.fieldAVal, 'String');
    % if isnumeric(handles.data.analysis.fieldAVal)
    %     handles.data.analysis.fieldAVal = num2str(handles.data.analysis.fieldAVal);
    % end
    handles.data.analysis.fieldAVal = '';
    set(handles.fieldAVal, 'String', handles.data.analysis.fieldAVal);

    % fieldBName
    handles.data.analysis.fieldBName = get(handles.fieldBName, 'String');
    if isnumeric(handles.data.analysis.fieldBName)
        handles.data.analysis.fieldBName = num2str(handles.data.analysis.fieldBName);
    end

    % fieldBVal
    % handles.data.analysis.fieldBVal = get(handles.fieldBVal, 'String');
    % if isnumeric(handles.data.analysis.fieldBVal)
    %     handles.data.analysis.fieldBVal = num2str(handles.data.analysis.fieldBVal);
    % end
    handles.data.analysis.fieldBVal = '';
    set(handles.fieldBVal, 'String', handles.data.analysis.fieldBVal);

    % fieldCName
    handles.data.analysis.fieldCName = get(handles.fieldCName, 'String');
    if isnumeric(handles.data.analysis.fieldCName)
        handles.data.analysis.fieldCName = num2str(handles.data.analysis.fieldCName);
    end

    % fieldCVal
    % handles.data.analysis.fieldCVal = get(handles.fieldCVal, 'String');
    % if isnumeric(handles.data.analysis.fieldCVal)
    %     handles.data.analysis.fieldCVal = num2str(handles.data.analysis.fieldCVal);
    % end
    handles.data.analysis.fieldCVal = '';
    set(handles.fieldCVal, 'String', handles.data.analysis.fieldCVal);

    % fieldDName
    handles.data.analysis.fieldDName = get(handles.fieldDName, 'String');
    if isnumeric(handles.data.analysis.fieldDName)
        handles.data.analysis.fieldDName = num2str(handles.data.analysis.fieldDName);
    end

    % fieldDVal
    % handles.data.analysis.fieldDVal = get(handles.fieldDVal, 'String');
    % if isnumeric(handles.data.analysis.fieldDVal)
    %     handles.data.analysis.fieldDVal = num2str(handles.data.analysis.fieldDVal);
    % end
    handles.data.analysis.fieldDVal = '';
    set(handles.fieldDVal, 'String', handles.data.analysis.fieldDVal);

    % fieldEName
    handles.data.analysis.fieldEName = get(handles.fieldEName, 'String');
    if isnumeric(handles.data.analysis.fieldEName)
        handles.data.analysis.fieldEName = num2str(handles.data.analysis.fieldEName);
    end

    % fieldEVal
    % handles.data.analysis.fieldEVal = get(handles.fieldEVal, 'String');
    % if isnumeric(handles.data.analysis.fieldEVal)
    %     handles.data.analysis.fieldEVal = num2str(handles.data.analysis.fieldEVal);
    % end
    handles.data.analysis.fieldEVal = '';
    set(handles.fieldEVal, 'String', handles.data.analysis.fieldEVal);

    % fieldFName
    handles.data.analysis.fieldFName = get(handles.fieldFName, 'String');
    if isnumeric(handles.data.analysis.fieldFName)
        handles.data.analysis.fieldFName = num2str(handles.data.analysis.fieldFName);
    end

    % fieldFVal
    % handles.data.analysis.fieldFVal = get(handles.fieldFVal, 'String');
    % if isnumeric(handles.data.analysis.fieldFVal)
    %     handles.data.analysis.fieldFVal = num2str(handles.data.analysis.fieldFVal);
    % end
    handles.data.analysis.fieldFVal = '';
    set(handles.fieldFVal, 'String', handles.data.analysis.fieldFVal);

    % fieldGName
    handles.data.analysis.fieldGName = get(handles.fieldGName, 'String');
    if isnumeric(handles.data.analysis.fieldGName)
        handles.data.analysis.fieldGName = num2str(handles.data.analysis.fieldGName);
    end

    % fieldGVal
    % handles.data.analysis.fieldGVal = get(handles.fieldGVal, 'String');
    % if isnumeric(handles.data.analysis.fieldGVal)
    %     handles.data.analysis.fieldGVal = num2str(handles.data.analysis.fieldGVal);
    % end
    handles.data.analysis.fieldGVal = '';
    set(handles.fieldGVal, 'String', handles.data.analysis.fieldGVal);

    % fieldHName
    handles.data.analysis.fieldHName = get(handles.fieldHName, 'String');
    if isnumeric(handles.data.analysis.fieldHName)
        handles.data.analysis.fieldHName = num2str(handles.data.analysis.fieldHName);
    end

    % fieldHVal
    % handles.data.analysis.fieldHVal = get(handles.fieldHVal, 'String');
    % if isnumeric(handles.data.analysis.fieldHVal)
    %     handles.data.analysis.fieldHVal = num2str(handles.data.analysis.fieldHVal);
    % end
    handles.data.analysis.fieldHVal = '';
    set(handles.fieldHVal, 'String', handles.data.analysis.fieldHVal);

end

% --------------- extract headerGUI info
if isfield(traceFile.header, 'headerGUI')
    hg = handles.data.map.mapActive.headerGUI;
end

% transfer the first map data set back to the active map directory:
handles.data.map.mapActive = handles.data.map.map1;
